package nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient implements Runnable {
    private boolean stop = false;
    private final String clientName;
    private Selector selector;
    private final int sleepSeconds;

    public NIOClient(String clientName, int sleepSeconds) {
        this.clientName = clientName;
        this.sleepSeconds = sleepSeconds;
    }

    @Override
    public void run() {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            // 连接方法也是异步的, 可能不会立刻完成
            if (socketChannel.connect(new InetSocketAddress("127.0.0.1", 16101))) {
                socketChannel.register(selector, SelectionKey.OP_READ);
                writeMsg(socketChannel);
            } else {
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }

            while (!this.stop) {
                selector.select();
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectedKeys.iterator();
                SelectionKey key;

                while (it.hasNext()) {
                    key = it.next();
                    it.remove();
                    handle(key);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handle(SelectionKey key) throws IOException, InterruptedException {
        if (key.isValid()) {
            SocketChannel sc = (SocketChannel) key.channel();
            if (key.isConnectable()) {
                if (sc.finishConnect()) {
                    Thread.sleep(this.sleepSeconds);
                    // 注册此通道可读标志
                    sc.register(selector, SelectionKey.OP_READ);
                    writeMsg(sc);
                } else
                    System.exit(1);
            }
            if (key.isReadable()) {
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String str = new String(bytes);
                    System.out.println(str);
                }
                this.stop = true;
                key.cancel();
                sc.close();
            }
        }
    }

    // 写消息
    private void writeMsg(SocketChannel socketChannel) throws IOException {
        byte[] req = ("Hello I`m " + this.clientName).getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        if (!writeBuffer.hasRemaining())
            System.out.println("Send order 2 server succeed.");
    }
}
